package net.sareweb.acab.entity.manager;

import java.util.Date;
import java.util.List;

import javax.persistence.NoResultException;

import net.sareweb.acab.entity.Avatar;
import net.sareweb.acab.entity.Dialog;
import net.sareweb.acab.entity.Travel;
import net.sareweb.acab.entity.User;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jfree.util.Log;

@Name("dialogManager")
@Scope(ScopeType.CONVERSATION)
public class DialogManager extends CommonManager<Dialog> {

	
	public boolean userHasUnreadDialogs(User u){
		if(u == null || u.getIdUser()==null) return false;
		return userHasUnreadDialogs(u.getIdUser());
	}
	
	public boolean userHasUnreadDialogs(Integer idUser){
		List<Dialog> d = entityManager.createQuery(_USER_HAS_UNREAD_DIALOGS)
    		.setParameter("idUser",idUser).getResultList();
		
		if(d==null || d.isEmpty())return false;
		return true;
	}
	
	public boolean travelHasUnreadDialogs(Travel t){
		if(t == null || t.getIdTravel()==null) return false;
		return travelHasUnreadDialogs(t.getIdTravel());
	}
	
	public boolean travelHasUnreadDialogs(Integer idTravel){
		List<Dialog> d = entityManager.createQuery(_TRAVEL_HAS_UNREAD_DIALOGS)
    		.setParameter("idTravel",idTravel).getResultList();
		
		if(d==null || d.isEmpty())return false;
		return true;
	}
	
	public void updateDialogOwnerSeenDate(Dialog d){
		d.setOwnerSeenDate(new Date());
		entityManager.persist(d);
	}
	

	public void updateDialogOtherSeenDate(Dialog d){
		d.setOtherSeenDate(new Date());
		entityManager.persist(d);
	}
	
	
	public Dialog findByTravelOtherUser(Integer travelId, Integer userId){
		System.out.println("travelId " + travelId + " userId " + userId);
		Dialog d = null;
		try{
			return (Dialog) entityManager.createQuery(_FIND_BY_TRAVEL_OTHER_USER)
				.setParameter("idTravel", travelId)
				.setParameter("idUser", userId).getSingleResult();
		}
		catch (NoResultException e) {
			System.out.println("2 travelId " + travelId + " userId " + userId);
			return null;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Dialog> findDialogByUser(Integer userId){
			return  entityManager.createQuery(_FIND_DIALOGS_BY_USER)
				.setParameter("idUser", userId).getResultList();
		
	}
	
	
	
	private String _USER_HAS_UNREAD_DIALOGS="from Dialog where  travel.user.idUser=:idUser and (ownerSeenDate is NULL  or  ownerSeenDate < lastCommentDate)";
	private String _TRAVEL_HAS_UNREAD_DIALOGS="from Dialog where  travel.idTravel=:idTravel and (ownerSeenDate is NULL  or  ownerSeenDate < lastCommentDate)";
	private String _FIND_BY_TRAVEL_OTHER_USER="from Dialog where  travel.idTravel=:idTravel and user.idUser=:idUser";
	private String _FIND_DIALOGS_BY_USER="from Dialog where user.idUser=:idUser";
	
}
